package com.jt.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jt.mapper.CartMapper;
import com.jt.pojo.Cart;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Author: Li Yu
 * @Date: 2020/11/19 19:57
 */
@Service
public class DubboCartServiceImpl implements DubboCartService {
    @Autowired
    private CartMapper cartMapper;


    @Override
    public List<Cart> findCartListByUserId(Long userId) {
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return cartMapper.selectList(queryWrapper);
    }

    /**
     * Sql: update tb_cart set num=#{num},updated=#{updated}
     *      where user_id=#{userId} and item_id = #{itemId}
     * @param cart
     */
    @Override
    public void updateCartNum(Cart cart) {
        Cart cartTemp = new Cart();
        cartTemp.setNum(cart.getNum());
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId())
                .eq("item_id", cart.getItemId());
        cartMapper.update(cartTemp,queryWrapper);
        //参数1: 封装set条件   参数2:封装where条件
    }

    @Override
    public void deleteCart(Cart cart) {
        cartMapper.delete(new QueryWrapper<>(cart));
    }

    /**
     * 如果购物车已存在商品，商品数量增加，否则新增
     * 如何判断购物车是否存在 userId itemId
     * @param cart
     */
    @Override
    public void addCart(Cart cart) {
        QueryWrapper<Cart> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id", cart.getUserId());
        queryWrapper.eq("item_id", cart.getItemId());
        Cart cartDB=cartMapper.selectOne(queryWrapper);
        if (cartDB==null){
            //第一次，新增购物车
            cartMapper.insert(cart);
        }else {
            //用户已经加购，更新数量
            int num=cartDB.getNum()+cart.getNum();
            Cart cartTemp=new Cart();
            cartTemp.setNum(num).setId(cartDB.getId());
            cartMapper.updateById(cartTemp);
        }
    }
}
